﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using iMapa.Utils;

namespace iMapa.Backend
{
    public class ActionExecutor
    {
        InteractMapGroup img;

        ExecutionQueue execQueue;

        public void ProcessFoundSpotPoint(Point p)
        {
            List<InteractMap> calibratedMaps=img.CurrentDetected();
            foreach (InteractMap map in calibratedMaps)
            {
                PointF? modelSpot = GetModelSpot(map,p);
                if (modelSpot.HasValue)
                {
                    foreach (InteractObject io in map.InteractObjects)
                    {
                        if (IsInteractObjectFired(io, modelSpot.Value))
                        {
                            execQueue.Enqueue(io);
                        }
                    }
                }
                else
                {
                    execQueue.Enqueue(null);
                }
            }

        }

        private bool IsInteractObjectFired(InteractObject io, PointF pointF)
        {
            double distance = Math.Sqrt(Math.Pow(Math.Abs(io.Position.X - pointF.X), 2.0) + Math.Pow(Math.Abs(io.Position.Y - pointF.Y), 2.0));
            if (distance <= (io.Radius/2))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private PointF? GetModelSpot(InteractMap map,Point p)
        {
            PointF? mPoint = map.CountProjectionPoint(ImgUtils.ToPointF(p),true);

            if (mPoint.Value!=null && mPoint.Value.X >= 0 && mPoint.Value.X <= map.ModelImage.Width && mPoint.Value.Y >= 0 && mPoint.Value.Y <= map.ModelImage.Height)
            {
                return mPoint.Value;
            }
            return null;
        }


        public void InitExecution(InteractMapGroup img)
        {
            this.img = img;
            execQueue = new ExecutionQueue();
        }

        public void ResetExecution()
        {
            execQueue.Reset();
        }
    }
}
